﻿Imports System.Text
Imports Microsoft.SharePoint.Publishing
Imports System.IO
Imports Microsoft.SharePoint.Administration

Public Class BuilderMain
    Private _siteURL As String
    Private _SiteID As Guid

    Dim textWriter As StringBuilder = Nothing
    Dim dateFormatString As String = "yyyy'-'MM'-'dd"
    'Public Sub New(ByVal siteUrl As String)
    '    _siteURL = siteUrl
    'End Sub
    Public Sub New(ByVal siteID As Guid)
        _SiteID = siteID
    End Sub
    Public Sub New(ByVal Url As String)
        Dim st As New SPSite(Url)

        _SiteID = st.ID
    End Sub

    Public Sub Run()
        Try
            textWriter = New StringBuilder(String.Empty)
            '     Dim intsite As SPSite = New SPSite(_siteURL)
            '  _SiteID = intsite.ID
            Dim site As SPSite = New SPSite(_SiteID, SPUrlZone.Internet)
            With site
                Dim web As SPWeb = site.RootWeb
                With web
                    textWriter.AppendLine("<?xml version=""1.0"" encoding=""UTF-8""?>")
                    textWriter.AppendLine("<urlset xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"" xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">")
                    LoadTreeViewForSubWebs(web) ' kick it off with the root web As 
                    textWriter.AppendLine("</urlset>")
                    Dim stream As MemoryStream = New MemoryStream(Encoding.UTF8.GetBytes(textWriter.ToString()))
                    web.Files.Add("sitemap.xml", stream, True)
                    stream.Close()
                End With
            End With


            'try

        Catch ex As Exception
            errorHandler(ex, "BuildSitemap")
        End Try
    End Sub

    Private Sub LoadTreeViewForSubWebs(ByVal currentWeb As SPWeb)
        '/ <summary>
        '/ LoadTreeViewForSubWebs()
        '/ Writes a node for a SPWeb.  Will call itself recursively if 
        '/ currentWeb has sub webs.
        '/ Will call LoadTreeViewForSubWebPages for the web's pages.
        '/ </summary>
        '/ <requirements></requirements>
        '/ <author>Tim Dobrinski, edited by Chris Prime</author>
        '/ <date>February 27, 2008</date>
        '/ <exceptions></exceptions>
        '/ <return></return>
        '/ <param name=””>SPWeb currentWeb</param>
        '/ <calledBy>BuildSitemap, self(recursive)</calledBy>
        '/ <edit>
        '/ Author: Tim Dobrinski 
        '/ Date:   3/4/8
        '/ Edit:   Added the using statement to better control memory usage with SPWebs
        '/ Edit:   Added SPFile _file = web.GetFile(web.Url.ToString() + "nopost.xml");
        '/               if(!_file.Exists) {}
        '/         in order to give a way to hide sections of the site that shouldn't be 
        '/         posted in the SiteMap.xml file since there is no way to exclude content 
        '/         from the search with just a SiteMap.xml file.  
        '/ </edit>
        Dim pPageCol As PublishingPageCollection = Nothing
        Dim tagLabel As String = String.Empty
        ' If (currentWeb.AllowAnonymousAccess) Then
        If PublishingWeb.IsPublishingWeb(currentWeb) Then
            Dim pWeb As PublishingWeb = PublishingWeb.GetPublishingWeb(currentWeb)
            pPageCol = pWeb.GetPublishingPages()
        End If
        'create xml link to site
        'to remove the link to the site (without a page), remove the next line
        writeSitemapNode(currentWeb.Url + "/", currentWeb.LastItemModifiedDate.ToString(dateFormatString))

        'create xml links to site pages
        If Not pPageCol Is Nothing Then
            LoadTreeViewForSubWebPages(pPageCol)
            pPageCol = Nothing
        End If
        For Each web As SPWeb In currentWeb.Webs
            Dim _file As SPFile = web.GetFile(web.Url.ToString() + "nopost.xml")
            If Not _file.Exists Then
                LoadTreeViewForSubWebs(web)
            End If
        Next
        'End If
        currentWeb.Close()

    End Sub

    Private Sub LoadTreeViewForSubWebPages(ByVal currentPages As PublishingPageCollection)
        Dim page As PublishingPage
        For Each page In currentPages
            If page.Url.EndsWith("aspx") Then
                If page.ListItem.HasPublishedVersion Then
                    writeSitemapNode(page.PublishingWeb.Url + "/" + page.Url, page.LastModifiedDate.ToString(dateFormatString))
                End If

            End If
        Next
    End Sub

    Private Sub writeSitemapNode(ByVal pageLocation As String, ByVal lastModified As String)
        textWriter.AppendLine(vbTab + "<url>")
        'replace secured links with non-secured links
        textWriter.AppendLine(vbTab + vbTab + "<loc>" + pageLocation.Replace("https:", "http:") + "</loc>")
        textWriter.AppendLine(vbTab + vbTab + "<lastmod>" + lastModified + "</lastmod>")
        textWriter.AppendLine(vbTab + "</url>")
    End Sub


    Private Sub errorHandler(ByVal errorMessage As Exception, ByVal errorLocation As String)

        Try
            Dim _eventLog As System.Diagnostics.EventLog = New System.Diagnostics.EventLog("Timer Jobs")
            _eventLog.Source = "Sitemap Generator"
            _eventLog.WriteEntry("Error (" + errorLocation.ToString() + "): " + errorMessage.Message.ToString())
            _eventLog.Close()
            _eventLog = Nothing
        Catch

        End Try
    End Sub
End Class
